package com.xzg.gulimall.seckill.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xzg.gulimall.seckill.feign.CouponFeignService;
import com.xzg.gulimall.seckill.feign.ProductFeignService;
import com.xzg.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.xzg.gulimall.seckill.service.SeckillService;
import com.xzg.gulimall.seckill.to.SeckillSkuRedisTo;
import com.xzg.gulimall.seckill.vo.SeckillSessionWithSkus;
import com.xzg.gulimall.seckill.vo.SeckillSkuVo;
import com.xzg.gulimall.seckill.vo.SkuInfoVo;
import com.xzh.common.to.mq.SeckillOrderTo;
import com.xzh.common.utils.R;
import com.xzh.common.vo.MemberRespVo;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    RedissonClient redissonClient;
    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";
    private final String SKU_STOVK_SEMAPHORE = "seckill:stock:";//+商品随机码

    @Override
    public void uploadSeckillSkuLatest3Days() {
        //扫描最近三天需要参与秒杀的活动
        R session = couponFeignService.getLastest3DaySession();
        if(session.getCode()==0){
            //上架商品
            List<SeckillSessionWithSkus> sessionData = session.getData(new TypeReference<List<SeckillSessionWithSkus>>() {
            });
            //缓存到redis
            //1、活动信息
            saveSessionInfo(sessionData);
            //2、活动的关联商品信息
            saveSessionSkuInfo(sessionData);
        }
    }

    //获取当前可以参与秒杀的商品信息
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        //确定当前时间属于哪个秒杀场次
        Long time = new Date().getTime();
        Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
        for (String key : keys) {
            String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
            String[] s = replace.split("_");
            Long start = Long.parseLong(s[0]);
            Long end = Long.parseLong(s[1]);
            if(start<=time && time<=end){
                //获取这个秒杀场次的所有商品信息
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);

                BoundHashOperations<String, String, SeckillSkuRedisTo> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                List<SeckillSkuRedisTo> list = ops.multiGet(range);

                if(list!=null){
                    return list;
                }
                break;
            }
        }
        return null;
    }

    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        //找到所有需要参与秒杀的商品key
        BoundHashOperations<String, String, String> ops = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = ops.keys();
        if(keys!=null&&keys.size()>0){
            String regx = "\\d_"+skuId;
            for (String key : keys) {
               if(Pattern.matches(regx,key)){

                   String s = ops.get(key);
                   SeckillSkuRedisTo skuRedisTo = JSON.parseObject(s, SeckillSkuRedisTo.class);
                   System.out.println(skuRedisTo);
                   //随机码
                   Long current = new Date().getTime();
                   Long startTime = skuRedisTo.getStartTime();
                   Long endTime = skuRedisTo.getEndTime();
                   if(current>=startTime&&current<=endTime){

                   }else{
                       //不是当前秒杀时间，随机码置空
                       skuRedisTo.setRandomCode(null);
                   }
                   return skuRedisTo;
               }
            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {
        MemberRespVo respVo = LoginUserInterceptor.LoginUser.get();
        //获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> ops = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String s = ops.get(killId);
        if (StringUtils.isEmpty(s)) {
            return null;

        } else {
            SeckillSkuRedisTo redis = JSON.parseObject(s, SeckillSkuRedisTo.class);
            //校验合法性
            Long startTime = redis.getStartTime();
            Long endTime = redis.getEndTime();
            long time = new Date().getTime();
            Long ttl = endTime - time;
            //校验时间合法性
            if (time >= startTime && time <= endTime) {
                //2、校验随机码和商品ID
                String randomCode = redis.getRandomCode();
                String id = redis.getPromotionSessionId() + "_" + redis.getSkuId();
                if (randomCode.equals(key) && killId.equals(id)) {
                    //3、验证购物数量是否合理
                    if (num <= redis.getSeckillLimit().intValue()) {
                        //4、验证这个人是否已经购买过，幂等性处理；如果秒杀成功就去占位  userId_sessionId_skuId
                        String redisKey = respVo.getId() + "_" + id;
                        //自动过期
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean) {
                            //占位成功，说明没买过
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOVK_SEMAPHORE + randomCode);

                            boolean b = semaphore.tryAcquire(num);
                            if (b) {
                                //秒杀成功
                                //快速下单，发送MQ消息
                                String timeId = IdWorker.getTimeId();
                                SeckillOrderTo orderTo = new SeckillOrderTo();
                                orderTo.setOrderSn(timeId);
                                orderTo.setMemberId(respVo.getId());
                                orderTo.setNum(num);
                                orderTo.setPromotionSessionId(redis.getPromotionSessionId());
                                orderTo.setSkuId(redis.getSkuId());
                                orderTo.setSeckillPrice(redis.getSeckillPrice());
                                rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", orderTo);
                                return timeId;
                            } else {
                                return null;
                            }


                        } else {
                            //已经买过了
                            return null;
                        }

                    }
                } else {
                    return null;
                }
            } else {
                return null;
            }

        }
        return null;
    }

    private void saveSessionInfo(List<SeckillSessionWithSkus> sessions){
        if(sessions!=null) {
            sessions.stream().forEach(session -> {
                Long startTime = session.getStartTime().getTime();
                Long endTime = session.getEndTime().getTime();
                String key = startTime + "_" + endTime;
                Boolean hask = redisTemplate.hasKey(SESSIONS_CACHE_PREFIX + key);
                //缓存活动信息
                if (!hask) {
                    List<String> collect = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId().toString() + "_" + item.getSkuId().toString()).collect(Collectors.toList());
                    redisTemplate.opsForList().leftPushAll(SESSIONS_CACHE_PREFIX + key, collect);
                }
            /*List<String> collect = session.getRelationSkus().stream().map(item->item.getPromotionSessionId()+"_"+item.getSkuId().toString()).collect(Collectors.toList());
            redisTemplate.opsForSet().add(SESSIONS_CACHE_PREFIX + key, collect);*/
            });
        }

    }
    private void saveSessionSkuInfo(List<SeckillSessionWithSkus> sessions){
        if(sessions!=null){
        sessions.stream().forEach(session -> {
            BoundHashOperations ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            session.getRelationSkus().stream().forEach(seckillSkuVo -> {
                //设置随机码 （类似于图片验证码）
                String token = UUID.randomUUID().toString().replace("-", "");
                if(!ops.hasKey(seckillSkuVo.getPromotionSessionId().toString()+"_"+seckillSkuVo.getSkuId().toString())) {
                    //缓存商品
                    SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                    //sku基本数据
                    R skuInfo = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                    if (skuInfo.getCode() == 0) {
                        SkuInfoVo info = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfo(info);
                    }
                    //sku秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo, redisTo);

                    //设置当前商品的秒杀时间信息
                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());
                    redisTo.setRandomCode(token);
                    ops.put(seckillSkuVo.getPromotionSessionId().toString()+"_"+seckillSkuVo.getSkuId().toString(), redisTo);
                    //如果当前这个场次的商品的库存信息已经上架就不需要上架
                    //使用库存作为分布式信号量 ---限流；
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOVK_SEMAPHORE + token);
                    //商品可以秒杀的数量作为信号量
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount().intValue());
                }
            });
        });

    } }
}
